# -*- coding: utf-8 -*-

import random
from binascii import b2a_hex, a2b_hex 
import base64
from Crypto.Cipher import AES

def get_public_key():#生成公钥
    #设定32位长度的范围
    a = 10000000000000000000000000000000
    b = 99999999999999999999999999999999
    #利用随机数生成公钥
    public_key = str(random.randint(a,b))
    
    return public_key

def encrypt(file,public_key):
    
    #补全信息的长度为16的倍数
    '''leth = len(file)
    file_add_num = 0
    if leth %  16 != 0:
        file_add_num = 16 - (leth %16)
    file_add = '\0' * file_add_num
    file_add = file_add.encode('utf - 8')
    file = file + file_add'''
    #设定初始量
    iv = public_key[0:16].encode('utf-8')
    
    #初始化一个对象cryptor
    aes_cryptor = AES.new(public_key.encode('utf-8'), AES.MODE_CFB,iv)

    #先进行aes加密
    aes_cryptor_file = aes_cryptor.encrypt(file)
    
    #16进制处理
    encrypt_file = base64.encodebytes(aes_cryptor_file)
    
    return encrypt_file.decode('utf-8')

def decrpt(encrypt_file,public_key):
    
    #设定初始量
    iv = public_key[0:16].encode('utf-8')
    
    #初始化一个对象cryptor
    aes_cryptor = AES.new(public_key.encode('utf-8'), AES.MODE_CFB,iv)
    
    #执行解密
    aes_cryptor_file = aes_cryptor.decrypt(base64.decodebytes(encrypt_file.encode('utf-8')))
    
    #解码并删掉多余字符
    file = aes_cryptor_file#.rstrip('')用来返回明文，如：“大创加油”
    #file = file.encode('utf-8') #再加上这行语句就会返回明文的二进制数据流
    return file
#小例子：
f = open('1.jpeg','rb')#（文件里的内容是：）大创加油！
file = f.read()
print(len(file))
print(file[10000:10100])
      #print(file)
key = get_public_key()
en = encrypt(file,key)
de = decrpt(en,key)
f.close()
print(en)
print(len(de))
print(de[10000:10100])





